<template>
	<view class="content">
		<view class="empty" v-if="orderList.length === 0">
			<uni-icons type="cart-filled" size="180" color="#cccccc"></uni-icons>
			<view class="tips-text">暂无订单</view>
			<button type="warn" class="btn" @click="toSortPage">去挑选</button>
		</view>
		<template v-for="order in orderList" :key="order.id">
			<uni-card :is-shadow="false" class="order-card">
				<template #title>
					<view class="order-card-title" @click="toOrderDetail(order)">
						<text>{{`订单号：${order.order_code}`}}</text>
						<uni-icons type="right"></uni-icons>
					</view>
				</template>
				<view class="product-list">
					<view class="product-item" v-for="product in order.items" :key="product.id">
						<image class="cover" :src="getFlowerCover(product.flower.images)"></image>
						<view class="info">
							<view class="name">{{ product.flower.name }}</view>
							<view class="price">{{ "￥" + numeral(product.flower.price).format("0.00") }}</view>
							<view class="quantity">{{ `x ${product.quantity}` }}</view>
						</view>
					</view>
				</view>
				<view class="total-price">
					{{ `实付款：￥${numeral(order.total_price).format("0.00")}` }}
				</view>
				<view class="order-card-actions">
					<button type="primary" size="mini" v-if="order.status === 1 && order.payment_status === 1"
						@click="handlePayment(order)">立即付款</button>
					<button size="mini" v-if="order.status === 1 && order.payment_status === 1"
						@click="handleCancelOrder(order)">取消订单</button>

					<uni-tag v-if="order.status === 1 && order.payment_status === 2 && order.shipping_status === 1"
						type="warning" text="等待配送" />

					<uni-tag v-if="order.status === 1 && order.payment_status === 2 && order.shipping_status === 2"
						type="warning" text="配送中" />

					<button size="mini"
						v-if="order.status === 1 && order.payment_status === 2 && order.shipping_status === 1"
						@click="handleRefundOrder(order)">申请退款</button>

					<button size="mini" disabled v-if="order.status === 2">已完成</button>

					<button size="mini" disabled v-if="order.status === 3 && order.payment_status === 1">已取消</button>

					<button size="mini" disabled v-if="order.status === 3 && order.payment_status === 3">已退款</button>
				</view>
			</uni-card>
		</template>

		<PaymentModal ref="paymentModalRef" @paid="loadOrders" />
	</view>
</template>

<script setup>
	import {
		reactive,
		ref
	} from 'vue';
	import {
		OrderListPageMode
	} from "@/constants/index.js"
	import {
		onLoad,
		onShow
	} from "@dcloudio/uni-app"
	import {
		SERVER_URL
	} from "@/config/index.js"
	import {
		useUserStore
	} from "@/stores/user.js"
	import {
		getFlowerCover
	} from "@/utils/index.js"
	import numeral from 'numeral';
	import PaymentModal from './components/PaymentModal.vue';

	const userStore = useUserStore()

	const state = reactive({
		pageMode: OrderListPageMode.All
	})

	const toSortPage = () => {
		uni.switchTab({
			url: "/pages/sort/sort"
		})
	}

	const orderList = ref([])

	const loadOrders = () => {
		uni.showLoading({
			title: "加载订单..."
		})
		uni.request({
			url: SERVER_URL + '/customer/order/all',
			method: "GET",
			data: {
				order_status: state.pageMode
			},
			header: {
				"authorization": userStore.token
			},
			success: (res) => {
				if (res.statusCode === 200) {
					orderList.value = res.data
				}
			},
			complete: () => {
				uni.hideLoading()
			}
		});
	}

	const setPageTitle = () => {
		let title = ""
		switch (state.pageMode) {
			case OrderListPageMode.All:
				title = "全部订单"
				break
			case OrderListPageMode.UNPAID:
				title = "待支付订单"
				break
			case OrderListPageMode.NOT_SHIPPED:
				title = "待配送订单"
				break
			case OrderListPageMode.IN_SHIPPED:
				title = "配送中订单"
				break
			case OrderListPageMode.DONE:
				title = "已完成订单"
				break
			case OrderListPageMode.REFUNDED:
				title = "已退款订单"
				break
			default:
				title = "订单列表"
				break
		}

		uni.setNavigationBarTitle({
			title
		})
	}

	const handleCancelOrder = (order) => {
		uni.showModal({
			title: "确认要取消订单？",
			success: (res) => {
				if (res.confirm) {
					uni.showLoading()
					uni.request({
						url: SERVER_URL + '/customer/order/cancel/' + order.id,
						method: "PUT",
						header: {
							"content-type": "application/json",
							"authorization": userStore.token
						},
						success: (res) => {
							if (res.statusCode === 200) {
								uni.showToast({
									icon: "success",
									title: "订单已取消"
								})
							}
						},
						complete: () => {
							uni.hideLoading()
							setTimeout(() => {
								loadOrders()
							}, 1500)
						}
					});
				}
			}
		})
	}

	const handleRefundOrder = (order) => {
		uni.showModal({
			title: "确认要申请退款？",
			success: (res) => {
				if (res.confirm) {
					uni.showLoading()
					uni.request({
						url: SERVER_URL + '/customer/order/refund/' + order.id,
						method: "PUT",
						header: {
							"content-type": "application/json",
							"authorization": userStore.token
						},
						success: (res) => {
							if (res.statusCode === 200) {
								uni.showToast({
									icon: "success",
									title: "退款成功"
								})
							}
						},
						complete: () => {
							uni.hideLoading()
							setTimeout(() => {
								loadOrders()
							}, 1500)
						}
					});
				}
			}
		})
	}

	const paymentModalRef = ref()
	const handlePayment = (order) => {
		paymentModalRef.value.show(order.id)
	}

	const toOrderDetail = (e) => {
		uni.navigateTo({
			url: "/pages/order/detail?id=" + e.id
		})
	}

	onLoad((e) => {
		if (!isNaN(Number(e.mode))) state.pageMode = Number(e.mode)
		setPageTitle()
	})

	onShow(() => {
		loadOrders()
	})
</script>

<style scoped lang="scss">
	.content {
		min-height: 100vh;
		background-color: #F2F6FD;
		overflow: hidden;

		.empty {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding-top: 4rem;

			.tips-text {
				color: #cccccc;
			}

			.btn {
				margin-top: 4rem;
				padding: 0 24px;
			}
		}

		.order-card {
			.order-card-title {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 10px 0;
				border-bottom: 1px solid #eeeeee;

				.uni-icons {
					line-height: 1;
				}
			}

			:deep(.uni-card__content) {
				padding: 10px 0 !important;
			}

			.product-list {
				.product-item {
					display: flex;
					align-items: center;

					.cover {
						width: 80px;
						height: 80px;
						margin-right: 10px;
					}

					.info {
						flex: 1;
						height: 80px;
						display: flex;
						flex-direction: column;
						overflow: hidden;

						.name {
							overflow: hidden;
							text-overflow: ellipsis;
							white-space: nowrap;
						}

						.price {
							margin-top: 12px;
							color: #ee0a24;
						}

						.quantity {
							font-size: 14px;
							color: #666;
							text-align: right;
						}
					}
				}

				.product-item:nth-of-type(n+2) {
					margin-top: 10px;
				}
			}

			.total-price {
				padding-top: 10px;
				text-align: right;
				font-weight: 700;
			}

			.order-card-actions {
				margin-top: 10px;
				padding-top: 10px;
				border-top: 1px solid #eeeeee;
				display: flex;
				align-items: center;
				justify-content: flex-end;
				gap: 6px;

				button {
					margin: 0;
				}
			}
		}
	}
</style>